package com.motu.vertx.module.utility.vertx;

import com.motu.vertx.module.utility.base.ServerConfig;
import com.motu.vertx.module.utility.redis.RedisTools;
import io.vertx.core.*;
import io.vertx.core.json.JsonObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class VerticleTool {
    private static final Logger logger = LoggerFactory.getLogger(RedisTools.class);
    public static Future<String> deployVerticleIfNeeded(Vertx vertx, String verticle, DeploymentOptions options) {
        Promise<String> promise = Promise.promise();
        if (options.getInstances() == 0) {
            logger.error("{} deployVerticle instance num is 0!!", verticle);
            promise.fail("instance num is 0");
        } else {
            vertx.deployVerticle(verticle, options, promise);
        }
        return promise.future();
    }

    /***
     * 获取verticle发布的配置（适用于已经初始化过游戏配置）
     * @param name   配置文件中的key名
     * @param defaultNum 默认数量
     * @param threadingModel 线程模式
     * @return 部署配置
     */
    public static DeploymentOptions getDeploymentOptions(String name, int defaultNum, ThreadingModel threadingModel){
        return getDeploymentOptions(ServerConfig.getAppConfig(), name, defaultNum, threadingModel);
    }

    /***
     * 获取verticle发布的配置
     * @param config json配置文件
     * @param name   配置文件中的key名
     * @param defaultNum 默认数量
     * @param threadingModel 线程模式
     * @return 部署配置
     */
    public static DeploymentOptions getDeploymentOptions(JsonObject config, String name, int defaultNum, ThreadingModel threadingModel){
        DeploymentOptions option = new DeploymentOptions()
                .setConfig(config)
                .setThreadingModel(threadingModel)
                .setInstances(config.getInteger(name, defaultNum));
        return  option;
    }

    public static <T> Handler<AsyncResult<T>> reporter(Promise<Void> future) {
        return ar -> {
            if (ar.succeeded()) {
                logger.info("reporter success !!!!");
                //            	System.out.println("deployVerticle success size = " + MainVerticle.instance.vertxInstance.deploymentIDs().size());
                future.complete();
            } else {
                logger.info("reporter error !!!!");
                ar.cause().printStackTrace();
                future.fail(ar.cause());
            }
        };
    }

    public static void asyncMethod(Handler<AsyncResult<Void>> onComplete) {
        onComplete.handle(Future.succeededFuture());
    }
}
